var MAIL = {	
    /*
     * function for sidebal
     * Mrhoang
     *
     */
    /**
     * edit contact name
     */
	Trim:function(sString){
        while (sString.substring(0, 1) == ' ') {
            sString = sString.substring(1, sString.length);
        }
        while (sString.substring(sString.length - 1, sString.length) == ' ') {
            sString = sString.substring(0, sString.length - 1);
        }
        return sString;
    },
	timkiemDB:function(page)
	{	
	var url = COREJS._getJsLang('_GENCRM_URL')+'/modules/mail/contact/getcontactlit?page='+page;
		$.getJSON(url,$('#seachcontac').serialize(),function(data){
			$('#contactllistcr').html(data.listadd);
			$('#paging').html(data.pagination);
		});
	},
	chondanhba:function(fn)
	{
		if(fn === 1)
		{
			$('#customer').attr('disabled','');
			$('#contactformemail').attr('disabled','disabled');
		}
		else
		{
			$('#customer').attr('disabled','disabled');
			$('#contactformemail').attr('disabled','');
		}
	},
	getcontactcr:function ()
	{
		$("#popupemailcr").css("padding", "0px");
		$("#popupemailcr").dialog("open");
		var	url =  COREJS._getJsLang('_GENCRM_URL')+'/modules/mail/contact/getcontact';
		$.getJSON(url,null,function(data){
			$("#emailcontact").html(data.listct);
			$('#listcontact2').html(data.listct2);
		});
	},
	fnselectemail:function(sl)
	{
		if(sl == 1)
		{
			$('#sendcontact').css('display','block');
			$('#sendemail').css('display','none');
		}else
		{
			$('#sendcontact').css('display','none');
			$('#sendemail').css('display','block');
		}
	},
	selectemail:function()
	{
		var str = "";
		var stradd = $("#to_addresses").val();
		$("#address-body input[type= 'checkbox']").each(function(){
			if ($(this).is(":checked")) {
				if(str!="")
				{
					str+=', '
				}
				var ktt = $('#name_'+($(this).val())).html();
				if(ktt!="")
				{
					str+='"'+$('#name_'+($(this).val())).html()+'"  ';
				}
				str+='<'+$('#adress_'+($(this).val())).html()+'>';
			}
		});
		if (str == "")
		{
			COREJS.AlertMsg('Báº¡n chÆ°a chá»�n email nÃ o.');
			return false;
		}
		if(stradd!="")
		{
			str+= ", ";
		}
		$("#to_addresses").val(stradd+str);
		$("#contact").dialog("close");
	},
	selectAll:function(id,idcheckbox)
	{
		if($("#"+idcheckbox).is(":checked"))
		{
			$("#"+ id+ " input[type= 'checkbox']").each(function(){
			$(this).attr("checked", true);
			
				});
		}
		else
		{
			$("#"+ id+ " input[type= 'checkbox']").each(function(){
			$(this).attr("checked", false);
			
				});
		}
		
	},
	selecthis:function(name,add)
	{
		$("#contact").dialog("close");
		$txtadd = $("#to_addresses").val();
		$("#to_addresses").val($txtadd+'"'+name+'" <'+add+'>,');
		
	},
	getlistAddress:function(id)
	{
		if ($('input[name="selectmail"]:checked').val() == 1) {
			var arrayid = $('#list_contact').val();
			var curcontact = $('#to_addresses').val();
			var url = COREJS._getJsLang('_GENCRM_URL') + '/modules/mail/contact/getcontactmultil?id=' + arrayid;
			$.getJSON(url, null, function(data){
				$('#to_addresses').val(curcontact + data);
				
			});
		}
		else{
			var str = "";
			$('#contactllistcr input[type="checkbox"]').each(function(){
				if($(this).is(':checked'))
				{
					
					if(($('#add_'+$(this).val()).html())!=''){
						if(str!="")
					{
						str+=',';
					}
					if(($('#name_'+$(this).val()).html())!=''){
						str+='"'+$('#name_'+$(this).val()).html()+'" ';	
					}
						str+=' <'+($('#add_'+$(this).val()).html())+'>';	
					}
				}
			});
			if (str != '') {
				str += ',';
			}
			if(str==''){
				alert(COREJS._getJsLang('EMAIL_EMPTY'));
				return false;
			}
			var curcontact = $('#to_addresses').val();
			$('#to_addresses').val(curcontact + str);
		}
		$('#popupemailcr').dialog('close');
	},
	getcontactajax:function (page)
	{
		var id = $('#contact_book').val();
		$("#contact").css("padding", "0px");
		var	url =  COREJS._getJsLang('_GENCRM_URL')+'/modules/mail/contact/getcontact?id='+id+"&page="+page;
		$.getJSON(url,null,function(data){
			$('#contactllist').html(data.listadd);
		});
	},
	getcontact:function ()
	{
		$("#contact").css("padding", "0px");
		$("#contact").dialog("open");
		var	url =  COREJS._getJsLang('_GENCRM_URL')+'/modules/mail/contact/getcontact';
		$.getJSON(url,null,function(data){
			$('#contactllist').html(data.listadd);
			$("#selectcontact").html(data.listct);
		});
	},

	loadsignature:function(url,id)
	{
		var urlaction  = url+"modules/mail/setting/loadsignature?id="+id;
		$.getJSON(urlaction,null,function(data){
			$('#signature').html(data.chuky);
		});
	},
	delete_draft:function(url)
	{
		var arow = new Array();
		var i =0;
		var dem = 0;
		$("#email-mainpage-wrapper input[type= 'checkbox']").each(function(){
			if($(this).is(':checked')){
				dem++;
				
				}
				});
		if(dem == 0)
		{
			COREJS.AlertMsg( COREJS._getJsLang('SELECT_MS_EMPTY'));
			return false;
		}
		$("#email-mainpage-wrapper input[type= 'checkbox']").each(function(){
			if($(this).is(':checked')){
			arow[i] = $(this).val();
			$('#ms_'+arow[i]).remove();
			i++;
			}
		});
		COREJS.AlertMsg(dem +COREJS._getJsLang('DARFT_DELETED'));
		$.getJSON(url+"modules/mail/index/deldraft?id="+arow);
		{
			$(document).ajaxStop(function(){
				location.reload(true);
			});
		}
	},
	locationaddF:function(url)
	{
		var arow = new Array();
		var i =0;
		var dem = 0;
		$("#email-mainpage-wrapper input[type= 'checkbox']").each(function(){
			if($(this).is(':checked')){
				dem++;
				
				}
				});
		if(dem == 0)
		{
			COREJS.AlertMsg( COREJS._getJsLang('UNCHECK_EVRYONE'));
			return false;
		}
		$("#email-mainpage-wrapper input[type= 'checkbox']").each(function(){
			if($(this).is(':checked')){
			arow[i] = $(this).val();
			i++;
			}
		});
		window.location = url+"modules/mail/filter/add?idms="+arow;
	},
	showTipSp:function(Usercrete,timecreate,Userupdate,timeupdate){
	var tipWidth = 200;
	Tip('<div style="float:left;text-align:left; width:300px;"><b>Người tạo:</b>&nbsp; ' + Usercrete + "<br><b>Ngày tạo:</b>&nbsp; "+timeupdate+'<br><b>Người cập nhật:</b>&nbsp; '+Userupdate+"<br><b>Ngày cập nhật:</b>&nbsp; "+timecreate + 
	' </div>', SHADOW, true, SHADOWCOLOR, '#ffbbcc', BORDERCOLOR, '#555555', BGCOLOR, '#ffffe1', WIDTH, tipWidth);
	},
	unreport_spam:function(url)
	{
		var arow = new Array();
		var i =0;
		$("#email-mainpage-wrapper input[type= 'checkbox']").each(function(){
			if($(this).is(':checked')){
			arow[i] = $(this).val();
			$('#ms_'+arow[i]).remove();
			i++;
			}
		});
		if(i==0)
		{
			COREJS.AlertMsg( COREJS._getJsLang('SELECT_MS_EMPTY'));
		return false;
		}
		
		var urlaction = url+ "modules/mail/index/unreportspam?mowms="+arow;
		$.getJSON(urlaction);
		$(document).ajaxStop(function(){
			COREJS.AlertMsg(i+ COREJS._getJsLang('EMAILNOSPAM_MOVE_TO_INBOX'));
			window.location.reload(true);
		});
		
		
	},
	report_spam:function(url)
	{
		var arow = new Array();
		var i =0;
		$("#email-mainpage-wrapper input[type= 'checkbox']").each(function(){
			if($(this).is(':checked')){
			arow[i] = $(this).val();
			$('#ms_'+arow[i]).remove();
			i++;
			}
		});
		if(i==0)
		{
			COREJS.AlertMsg( COREJS._getJsLang('SELECT_MS_EMPTY'));
		return false;
		}
		
		var urlaction = url+ "modules/mail/index/reportspam?mowms="+arow;
		$.getJSON(urlaction);
		$(document).ajaxStop(function(){
			COREJS.AlertMsg(i+ COREJS._getJsLang('EMAIL_MOVE_TO_SPAM'));
			window.location.reload(true);
		});
		
		
	},
	delemailcontac:function(url)
	{
		var checked = new Array();
        var i = 0;
        var n = 0;
        var kt = 0;
        var urlaction = "";
        var str = new Array();
		var checkright = "";
        var n = $("#contactlist input:checked").length;
        if (n > 0) {
            kt = confirm(COREJS._getJsLang("SURE_DEL_CONTACT_EMAIL")+n+COREJS._getJsLang("SURE_DEL_CONTACT_SELECT"));
        }
		var dem = 0;
        if (kt) {
            $("#contactlist input[type = 'checkbox']").each(function(){
                if (this.checked) {
					dem+=Number($('#address_'+$(this).val()).html());
					if ($(this).next().val() == 0) {
					if(checkright!="")
					{
					checkright+=',';
					}
					checkright += " " + $(this).parent().next().html();
					}
					else
					{
					str[i] = $(this).val();
                    i++;
					}
                }
            });
			if(dem==0)
			{
				alert(COREJS._getJsLang('NOT_EMAIL_FOR_DEL'));
				return false;
			}
			var display_to = Number($('#display_to').text());
			display_to = display_to-i;
			$('#footer #display_to').text(display_to);
			$('#footer #totall').text(display_to);
            urlaction = url + "modules/mail/contact/emailincontact?idContact=" + str;
            $.getJSON(urlaction,null,function(data){
				if(data!=0)
				{
					alert(COREJS._getJsLang("NOT_DEL_ADD"));
				}
			});
			
        }
        if (checkright != "") {
		alert(COREJS._getJsLang("NOT_DEL_ADD_SHARE"));
			
		}
		$(document).ajaxStop(function()
		{
			location.reload(true);
		});
	},
	loadAcc:function(url)
	{
		urlaction = url + 'modules/mail/setting/loadacc';
		$.getJSON(urlaction,null,function(data){
			$('#select-account').html(data.selecbox);
			$('#signature').html(data.chuky);
			$('#row_page').val(data.SETTING_Row_per_page);
			$('#clean_trash_after').val(data.SETTING_Time_to_clean_Trash);
			$('#delete_spam_after').val(data.SETTING_Time_to_clean_Spam);
			$('#checkmail').val(data.SETTING_Time_to_check_mail);
			//alert(data);
		});
	}, 
	stopcheckacc:function()
	{
		$('#opencheckacc').html('');
		$("#info-checkmail").dialog("close");
	},
	miniwin_checkmail:function()
	{
		$('#opencheckacc').html('<a href = "#" >'+COREJS._getJsLang("DETECTED_MS")+'</a>');
		$("#info-checkmail").dialog("close");
	},
	load_acc:function(url)
	{	
		//$("#check_acc").html('');
		$("#info").dialog("open");
		$('#info').dialog({
			height: 400,
			width: 600,
		});
		$('#info .h-d-p').css('width','400px');
		$("#info").css("padding", "0px");
		/*
		$.getJSON(url+'modules/mail/index/detectms',null,function(data){
			$("#check_acc").html(data);
		});
		*/
		MAIL.v_fCheckMail(0);
	},
	checkkey:function(e,url,k)
	{
		var key;
     	if(window.event)
          key = window.event.keyCode;     //IE
	     else
	          key = e.which;     //firefox
	
	     if(key == 13)
		 {
		 	if(k==1)
			{
				this.chang_dirname(url);	
			}
			if(k==2)
			{
				this.create_new_dir(url);
			}
				 	
		 }
	},
	delete_ms_per:function(url)
	{
		var arow = new Array();
		var i =0;
		$("#email-mainpage-wrapper input[type= 'checkbox']").each(function(){
			if($(this).is(':checked')){
			arow[i] = $(this).val();
			$('#ms_'+arow[i]).remove();
			i++;
			}
		});
		if(i==0)
		{
			COREJS.AlertMsg( COREJS._getJsLang('SELECT_MS_EMPTY'));
		return false;
		}
		
		var urlaction = url+ "modules/mail/index/demail?mowms="+arow;
		$.getJSON(urlaction);
		$(document).ajaxStop(function(){
			COREJS.AlertMsg(i+ COREJS._getJsLang('EMAIL_DELETE_PER'));
			window.location.reload(true);
		});
		
		
	
	},
	delete_ms:function(url)
	{
		var arow = new Array();
		var i =0;
		$("#email-mainpage-wrapper input[type= 'checkbox']").each(function(){
			if($(this).is(':checked')){
			arow[i] = $(this).val();
			$('#ms_'+arow[i]).remove();
			i++;
			}
		});
		if(i==0)
		{
			COREJS.AlertMsg(COREJS._getJsLang('SELECT_MS_EMPTY'));
			return false;
		}
		var urlaction = url+ "modules/mail/index/markmail?isread=5&mowms="+arow;
		$.getJSON(urlaction);
		$(document).ajaxStop(function(){
			COREJS.AlertMsg(i+ COREJS._getJsLang('EMAIL_MOVED_TO_T'));
		});
		$(document).ajaxStop(function(){
			location.reload(true);
		});
	},
	mark_unstar:function(url)
	{
		var arow = new Array();
		var i =0;
		var k =0;
		var dem = 0;
		$("#email-mainpage-wrapper input[type= 'checkbox']").each(function(){
			if($(this).is(':checked')){
				dem++;
				
				}
				});
		if(dem == 0)
		{
			COREJS.AlertMsg(COREJS._getJsLang("UNCHECK_EVRYONE"));
			return false;
		}
		$("#email-mainpage-wrapper input[type= 'checkbox']").each(function(){
			if($(this).is(':checked')){
			arow[i] = $(this).val();
			$('#ms_'+arow[i]).addClass('mail-not-star');
			$('#ms_'+arow[i]).removeClass('mail-star');
			var divimg = $(this).parent().next();
			var objimg = divimg.find('img');
			objimg.attr('src',url+'images/icons/star1.png');
			i++;
			}
		});
		var urlaction = url+ "modules/mail/index/markmail?isread=4&mowms="+arow;
		$.getJSON(urlaction);
	},
	mark_star:function(url)
	{
		var arow = new Array();
		var i =0;
		var k =0;
		var dem = 0;
		$("#email-mainpage-wrapper input[type= 'checkbox']").each(function(){
			if($(this).is(':checked')){
				dem++;
				
				}
				});
		if(dem == 0)
		{
			COREJS.AlertMsg(COREJS._getJsLang("UNCHECK_EVRYONE"));
			return false;
		}
		$("#email-mainpage-wrapper input[type= 'checkbox']").each(function(){
			if($(this).is(':checked')){
			arow[i] = $(this).val();
			$('#ms_'+arow[i]).addClass('mail-star');
			$('#ms_'+arow[i]).removeClass('mail-not-star');
			var divimg = $(this).parent().next();
			var objimg = divimg.find('img');
			objimg.attr('src',url+'images/icons/star.png');
			i++;
			}
		});
		var urlaction = url+ "modules/mail/index/markmail?isread=3&mowms="+arow;
		$.getJSON(urlaction);
	},
	mark_uread:function(url)
	{
		var arow = new Array();
		var i =0;
		var k =0;
		var dem = 0;
		$("#email-mainpage-wrapper input[type= 'checkbox']").each(function(){
			if($(this).is(':checked')){
				dem++;
				}
				});
		if(dem == 0)
		{
			COREJS.AlertMsg(COREJS._getJsLang("UNCHECK_EVRYONE"));
			return false;
		}
		$("#email-mainpage-wrapper input[type= 'checkbox']").each(function(){
			if($(this).is(':checked')){
			arow[i] = $(this).val();
			$('#ms_'+arow[i]).css("font-weight","normal");
			$('#ms_'+arow[i]).css("background","#E0ECFF");
			$('#ms_'+arow[i]).removeClass('readed');
			$('#ms_'+arow[i]).addClass('mail-unread');
			i++;
			var cla = $(this).attr('class');
			if(cla == 'chua_doc')
				{
					k++;
				}
			$(this).addClass('doc');
			$(this).removeClass('chua_doc');
			}
			
		});
		//var l = Number($('#num_ms').text());
		//l = l-k;
		//$("#link_inbox").html(COREJS._getJsLang("IN_BOX")+'(<span id = "num_ms" >'+l+'</span>)');
		var urlaction = url+ "modules/mail/index/markmail?isread=0&mowms="+arow;
		$.getJSON(urlaction);
	},
	mark_read:function(url)
	{
		var arow = new Array();
		var i =0;
		var k =0;
		var dem = 0;
		$("#email-mainpage-wrapper input[type= 'checkbox']").each(function(){
			if($(this).is(':checked')){
				dem++;
				}
				});
		if(dem == 0)
		{
			COREJS.AlertMsg(COREJS._getJsLang("UNCHECK_EVRYONE"));
			return false;
		}
		$("#email-mainpage-wrapper input[type= 'checkbox']").each(function(){
			if($(this).is(':checked')){
			arow[i] = $(this).val();
			$('#ms_'+arow[i]).css("font-weight","bold");
			$('#ms_'+arow[i]).css("background","#FFFFCC");
			$('#ms_'+arow[i]).removeClass('mail-unread');
			$('#ms_'+arow[i]).addClass('readed');
			i++;
			var cla = $(this).attr('class');
			if(cla == 'chua_doc')
				{
					k++;
				}
			$(this).addClass('chua_doc');
			$(this).removeClass('doc');
			}
			
		});
		//var l = Number($('#num_ms').text());
		//i=i-k;
		//i=i+l;
		//$("#link_inbox").html(COREJS._getJsLang("IN_BOX")+'(<span id = "num_ms" >'+i+'</span>)');
		var urlaction = url+ "modules/mail/index/markmail?isread=1&mowms="+arow;
		$.getJSON(urlaction);
	},
	move_ms:function(url,id)
	{
		var arow = new Array();
		var i =0;
		$("#email-mainpage-wrapper input[type= 'checkbox']").each(function(){
			if($(this).is(':checked')){
			arow[i] = $(this).val();
			$('#ms_'+arow[i]).remove();
			i++;
			}
		});
		if(arow == "")
		{
			COREJS.AlertMsg(COREJS._getJsLang("UNCHECK_EVRYONE"));
			return false;
		}
		if(id == 'INBOX')
		{
			var urlaction = url + 'modules/mail/index/markmail?mowms='+arow+"&isread="+id;
		}
		else{
			var urlaction = url + 'modules/mail/index/moveMS?mowms='+arow+"&idid="+id;
		}
		
		$.getJSON(urlaction);
		$(document).ajaxStop(function(){
			location.reload(true);
		});
	},
    defaut: function(url, id){
        var urlaction = url + 'modules/mail/setting/defautacc?idacc=' + id;
        $.getJSON(urlaction);
        $('#accsenmail .clo-s').text(COREJS._getJsLang("AP_DEFAUT"));
        $('#accsenmail .clo-s').css('text-decoration', 'underline');
        $('#clo_2_' + id).text('Máº·c Ä‘á»‹nh');
        $('#clo_2_' + id).css('text-decoration', 'none');
        
    },
    delAcount: function(url, id){
        var kt = confirm(COREJS._getJsLang("SURE_DEL_ACC"));
        if (kt) {
            $("#rows_" + id).remove();
            var urlaction = url + "modules/mail/setting/delaccount?idacc=" + id;
            $.getJSON(urlaction);
        }
        
        
    },
    updateAcount: function(url, form){
        var email = $("#" + form + "  input[id = 'email_add']");
        if (!this.isEmail(email.val())) {
            email.focus();
            alert(COREJS._getJsLang("EMAIL_NOT_EMPTY"));
            return false;
        }
        var user = $("#" + form + "  input[id = 'Username']");
        if (user.val() == "") {
            user.focus();
            alert(COREJS._getJsLang("USER_NOT_EMPTY"));
            return false;
        }
        var pass = $("#" + form + "  input[id = 'Password']");
        /*
        if (pass.val() == "") {
            pass.focus();
            alert(COREJS._getJsLang("PASS_NOT_EMPTY"));
            return false;
        }
        */
        if ("add-acc-out" == form) {
            var urlaction = url + "modules/mail/setting/updateaccout?acctype=O";
            $("#acc-out-popup").dialog("close");
        }
        else {
            var urlaction = url + "modules/mail/setting/updateaccout?acctype=I";
            $("#acc-in-popup").dialog("close");
        }
        $.getJSON(urlaction, $("#" + form).serialize(), function(data){
            if ("add-acc-out" == form) {
                $('#clo_1_'+ data.idacount).html('<b>"' + data.namedisplay + '" &lt;' + data.email_add + "&gt; " + "</b>");
            }
            else 
                ("add-in-out" == form)
            {
                $('#cl_1_' + data.idacount).html('<b>"' + data.namedisplay + '" &lt;' + data.email_add + "&gt; " + "</b>");
            }
            
        });
        $("form").each(function(){
            this.reset();
        });
    },
    addAcount: function(url, form){
        var email = $("#" + form + "  input[id = 'email_add']");
        if (!this.isEmail(email.val())) {
            email.focus();
            alert(COREJS._getJsLang("EMAIL_FAID"));
            return false;
        }
        var user = $("#" + form + "  input[id = 'Username']");
        if (user.val() == "") {
            user.focus();
            alert(COREJS._getJsLang("USER_NOT_EMPTY"));
            return false;
        }
        var pass = $("#" + form + "  input[id = 'Password']");
        if (pass.val() == "") {
            pass.focus();
            alert(COREJS._getJsLang("PASS_NOT_EMPTY"));
            return false;
        }
        if ("add-acc-out" == form) {
            var urlaction = url + "modules/mail/setting/insertaccout";
            $("#acc-out-popup").dialog("close");
        }
        else {
            var urlaction = url + "modules/mail/setting/insertaccin";
            $("#acc-in-popup").dialog("close");
        }
        $.post(urlaction, $("#" + form).serialize(), function(data){
            if ("add-acc-out" == form) {
                $(data).insertBefore("#addaccountsed");
            }
            if ("add-acc-in" == form) {
                $(data).insertBefore("#addaccountresend");
            }
        });
        $("form").each(function(){
            this.reset();
        });
    },
    close_popup: function(id){
        $("#" + id).dialog("close");
		$("form").each(function(){
            this.reset();
        });
        $("#" + id + " #update").css("display", "none");
        $("#" + id + " #add").css("display", "block");
    },
    openpopup: function(url, div_id, id){
        if (id) {
            var urlaction = url + 'modules/mail/setting/getacountinfo?idacc=' + id;
            $.getJSON(urlaction, null, function(data){
                $("#" + div_id + " input[id ='namedisplay']").val(data.ACC_Namedisplay);
                $("#" + div_id + " input[id ='email_add']").val(data.ACC_Mail_Address);
                $("#" + div_id + " input[id ='smtp']").val(data.Server);
                $("#" + div_id + " input[id ='Username']").val(data.ACC_username);
                $("#" + div_id + " input[id ='Password']").val(data.Password);
                $("#" + div_id + " input[id ='Authenticaction']").val(data.Authenticaction);
                $("#" + div_id + " #encrypted").val(data.SSL);
                $("#" + div_id + " input[id ='smtp_port']").val(data.Port);
                $("#" + div_id + " input[id ='popserver']").val(data.Server);
                $("#" + div_id + " input[id ='pop_port']").val(data.Port);
                $("#" + div_id + " input[id ='idacount']").val(data.ACC_Id);
                $("#" + div_id + " input[id ='idconfig']").val(data.CONF_Id);
                if (data.ACC_authentication == 1) {
                    $("#" + div_id + " input[id ='Authenticaction']").attr('checked', true);
                }
                $("#" + div_id + " #update").css("display", "block");
                $("#" + div_id + " #add").css("display", "none");
            });
            
        }
        var sz_Title = '';
        if(div_id == 'acc-out-popup')
        {
        	if (id) {
        		sz_Title = COREJS._getJsLang("EDIT_ACC_OUT");
        	}
        	else {
        	 sz_Title = COREJS._getJsLang("ADD_ACC_OUT");
        	}
    	}
        else if(div_id == 'acc-in-popup')
        {
        	if (id){
        		sz_Title = COREJS._getJsLang("EDIT_ACC_IN");
        	}
        	else {
        		sz_Title = COREJS._getJsLang("ADD_ACC_IN");
        	}
        }
        $("#" + div_id).dialog("open");
        $("#" + div_id).dialog("option", 'title', sz_Title);
        $("#" + div_id).css("padding", "0px");
        $("#" + div_id).css("background-color", "white");
    },
    create_new_dir: function(url){
        var txtcolor = $("#text_color_cao").val();
        txtcolor = txtcolor.substr(1, txtcolor.length);
        var bgcolor = $("#bg_color_cao").val();
		var iscolor = $("#using_color").is(':checked');
        bgcolor = bgcolor.substr(1, bgcolor.length);
        if (bgcolor == "") {
            var bgcolor = $("#label_color").val();
            bgcolor = bgcolor.substr(1, bgcolor.length);
            txtcolor = "fff";
        }
        if (bgcolor == "") {
            bgcolor = "none";
        }
        if (txtcolor == "") {
            txtcolor = "fff";
        }
        var display = 0;
        var kt = $("#display").is(":checked");
        if (kt) {
            display = 1;
        }
        else {
            display = 0;
        }
        var praname = $("#label-name").val();
		if(praname == "")
		{
			alert(COREJS._getJsLang("DIR_NAME_NOT_EMPTY"));
			return false;
		}
		if(iscolor)
		{
			txtcolor = "";
			bgcolor = "none";
			
		}
        var urlaction = url + "modules/mail/index/addnewdir?name=" + praname + "&bgcolor=" + bgcolor + "&txtcolor=" + txtcolor + "&display=" + display;
        $.getJSON(urlaction, null, function(data){
            if (display == 1) {
               $(data.box).insertBefore("#menu-dir:eq(0)");
            }
            else {
              $(data.box).insertBefore("#side-box-other  ul:eq(0)");
                var num = Number($('#none-disp').text()) + 1;
                $('#none-disp').text(num);
            }
			$(data.dir).appendTo("#dir-wrapper");
        });
        $("#create-lable").dialog("close");
        $(document).ajaxStop(function(){
			window.location.reload(true);
		});
    },
    delete_color: function(id, url){
        var urlaction = url + "/modules/mail/index/delete_color?iddir=" + id;
        $.getJSON(urlaction);
        $(".dir-" + id).css("color", "#000");
        $(".dir-" + id).css("background-color", "#eee");
        
        $("#label-" + id).css("background-color", "#eee");
    },
    delete_dir: function(id, url){
        var kt = confirm(COREJS._getJsLang("SURE_DEL_DIR"));
        if (kt) {
            var urlaction = url + "modules/mail/index/deletedir?iddir=" + id;
            $.getJSON(urlaction);
            $("#menu_dir_" + id).remove();
            $(".dir-" + id).remove();
            $("#row_" + id).remove();
            $("#row1_" + id).remove();
			///COREJS.AlertMsg(COREJS._getJsLang('EMAIL_MOVE_TO_R'));
			$(document).ajaxStop(function(){
				//location.reload(true);
			});
        }
		
    },
    display_all: function(url){
        var coptext = $("#menu-dir .dir-row").clone();
        $("#menu-dir .dir-row").remove();
        coptext.insertBefore("#other-dir");
        urlaction = url + "modules/mail/index/changedisplay?display=" + 1;
        $("div[id^='un_display_']").addClass('link');
        $("div[id^='un_display_']").removeClass('unlink');
        $("div[id^='display_']").removeClass('link');
        $("div[id^='display_']").addClass('unlink');
        $.getJSON(urlaction);
    },
    un_display_all: function(url){
        var coptext = $("#menu-dir .dir-row").clone();
        $("#menu-dir .dir-row").remove();
        var dich = $("#all-message");
        coptext.insertBefore(dich);
        urlaction = url + "modules/mail/index/changedisplay?display=" + 0;
        
        $("div[id^='un_display_']").removeClass('link');
        $("div[id^='un_display_']").addClass('unlink');
        $("div[id^='display_']").addClass('link');
        $("div[id^='display_']").removeClass('unlink');
        $.getJSON(urlaction);
    },
    undisplay_dir: function(url, id){
			var cla = $("#un_display_"+id).attr('class'); 
			if(cla == 'colume unlink')
			return false;
			urlaction = url + "modules/mail/index/changedisplay?display=" + 0 + "&iddir=" + id;
			var coptext = "";
			coptext = $("#menu-dir > #menu_dir_" + id).clone();
			coptext.insertBefore("#all-message ");
			$("#menu-dir > #menu_dir_" + id).remove();
			$("#un_display_" + id).addClass('unlink');
			$("#un_display_" + id).removeClass('link');
			$("#display_" + id).removeClass('unlink');
			$("#display_" + id).addClass('link');
			var num = Number($('#none-disp').text()) + 1;
			$('#none-disp').text(num);
			$.getJSON(urlaction);
		
    },
    display_dir: function(url, id){
		var cla = $("#un_display_"+id).attr('class'); 
			if(cla == 'colume link')
			return false;
        var coptext = "";
        urlaction = url + "modules/mail/index/changedisplay?display=" + 1 + "&iddir=" + id;
        coptext = $("#side-box-other  #menu_dir_" + id).clone();
        coptext.insertBefore("#other-dir");
        $("#side-box-other  #menu_dir_" + id).remove();
        $("#display_" + id).removeClass('link');
        $("#display_" + id).addClass('unlink');
        $("#un_display_" + id).addClass('link');
        $("#un_display_" + id).removeClass('unlink');
        $.getJSON(urlaction);
        var num = Number($('#none-disp').text()) - 1;
        $('#none-disp').text(num);
    },
    chang_dirname: function(url){
        var id = $("#iddir").val();
        var name = $("#popup_mail_box_name").val();
		if(name == "")
		{
			alert(COREJS._getJsLang("DIR_NAME_NOT_EMPTY"));
			return false;
		}
        var urlaction = url + "modules/mail/index/updatedir?dirname=" + name + "&idirec=" + id;
        $.getJSON(urlaction);
        $("#popup_change_name").dialog("close");
        $("#label-" + id).next().text(name);
        $(".dir-" + id).text(name);
		$('#popup_mail_box_name').val(name);
		$("#popup_mail_box_name").ajaxStop(function(){
                location.reload(true);
            });
    },
    submit_ajax: function(url){
        var a = new Array();
        var i = 0;
        $("#updatedir input[type = 'text']").each(function(){
            str = $(this).attr("id");
            var id = str.substr(16, str.length)
            a[i] = id;
            $("#label-" + id).next().text($('#' + str).val());
            $(".dir-" + id).text($('#' + str).val());
            i++;
        });
        urlaction = url + "/modules/mail/index/updatedir?idinput=" + a;
        $.post(urlaction, $("#updatedir").serialize(), function(data){
            $("#updatedir").ajaxStop(function(){
                location.reload(true);
            });
        });
        $("#popup-foder-manage").dialog("close");
    },
    create_dir: function(url){
        var dirname = $("#create_folder").val();
		if(dirname == "")
		{
			alert(COREJS._getJsLang("DIR_NAME_NOT_EMPTY"));
			return false;
		}
        urlaction = url + "modules/mail/index/createdir?dirname=" + dirname;
        $.getJSON(urlaction)
            $("#create_folder").ajaxStop(function(){
			    window.location.reload(true);
            });
        
    },
    toglet: function(e){
        var curent = $(e).next();
        var k = $(e).next().attr("id");
        var _parent = $(e).parent().parent().parent().parent().attr("id");
        $("#" + _parent + " #" + k).toggle();
        if (_parent == "email-mainpage-footer") {
            $('.pop-wrr-mn-l').addClass('bottom');
			$('.pop-wrr-mn-l').removeClass('top');
        }
		else{
			$('.pop-wrr-mn-l').addClass('top');
			$('.pop-wrr-mn-l').removeClass('bottom');
		}
    },
    forcuskhachhang: function(){
        var idkh = $("#Kha_Id").val();
        $("#id_kh_dm").val(idkh);
    },
    import_cr: function(url, id){
        var str = "0";
        $("#addrelist_popup input[type = 'checkbox']").each(function(){
            if (this.checked) {
                str = str + "," + $(this).val();
            }
        });
        if (str == '0') {
            alert(COREJS._getJsLang("UN_SELECT_RECORD"));
            return false;
        }
        urlaction = url + "/modules/mail/contact/importcr?idimput=" + str + "&idcontact=" + id + '&optionsource=3';
        $.post(urlaction, $("#importcr").serialize(), function(data){
            $("#import_startus").text(data);
            
        });
        $("#button_1").css("display", "none");
        $("#button_2").css("display", "block");
    },
    import_dm: function(url, id){
        var str = "0";
        $("#addrelist_popup_dm input[type = 'checkbox']").each(function(){
            if (this.checked) {
                str = str + "," + $(this).val();
            }
        });
        if (str == '0') {
            alert(COREJS._getJsLang("UN_SELECT_RECORD"));
            return false;
        }
        urlaction = url + "/modules/mail/contact/importcr?idimput=" + str + "&idcontact=" + id + '&optionsource=4';
        $.post(urlaction, $("#importdm").serialize(), function(data){
            $("#import_startus_dm").text(data);
            
        });
        $("#button_3").css("display", "none");
        $("#button_4").css("display", "block");
    },
    check_all_cr: function(id, tb_id){
        var ischeck = $("#" + id).is(":checked");
        if (ischeck) {
            $("#" + tb_id + " input[type='checkbox']").attr("checked", true);
        }
        else {
            $("#" + tb_id + " input[type='checkbox']").attr("checked", false);
        }
        
    },
    getAddress_cr: function(url, idcontact){
        var cr_name = document.getElementById("khachhang").value;
        var cr_id = document.getElementById("Kha_Id").value;
        acr_id  = cr_id.split(',');
        acr_name = cr_name.split(',');
        for(i=0;i<acr_id.length;i++)
        	{
        	if(acr_id[i]){
        
        if (cr_name != "" && cr_id != "") {
            var urlaction = url + "/modules/mail/contact/getaddresscr?cr_name=" + acr_name[i] + "&cr_id=" + acr_id[i] + "&idcontact=" + idcontact;
            $.getJSON(urlaction, null, function(data){
            	var n = $("#addrelist_popup input[type='checkbox']").length + 1;
                var tr = "<tr><td><input  type = 'checkbox'  value = '" + n + "'  /></td><td>" + data.iCrName + "</td><td>" + data.Email + "</td><td>" + data.title + "</td><td>" + data.tartus + "</td></tr>";
                tr += "<input name = 'name_" + n + "' id = 'name_" + n + "' value = '" + data.iCrName + "' type = 'hidden' /><input  name = 'email_" + n + "'  id = 'email_" + n + "' value = '" + data.Email + "' type = 'hidden' /><input  name = 'title_" + n + "' id = 'title_" + n + "' value = '" + data.title + "' type = 'hidden' />";
                $(tr).appendTo("#addrelist_popup");
            });
        	}
        	}
        	}
        $("#khachhang").val("");
        $("#Kha_Id").val("");
    },
    getAddress_dm: function(url, idcontact){
    
        var dm_name = document.getElementById("_Ho_Ten").value;
        var dm_id = document.getElementById("Dml_Id").value;
        
        $("#id_kh_dm").val(dm_id);
        var adm_name = dm_name.split(',');
        var adm_id = dm_id.split(',');
       
        for(i=0;i<adm_name.length;i++)
    	{
        if (dm_name != "" && dm_id != "") {
            var urlaction = url + "/modules/mail/contact/gediachi?dm_name=" + adm_name[i] + "&idaumoi=" + adm_id[i] + "&idcontact=" + idcontact;
            $.getJSON(urlaction, null, function(data){
            	 var n = $("#addrelist_popup_dm input[type='checkbox']").length+1;
                var tr = "<tr><td><input  type = 'checkbox'  value = '" + n + "'  /></td><td>" + data.Ho_Ten + "</td><td>" + data.Email + "</td><td>" + data.title + "</td><td>" + data.tartus + "</td></tr>";
                tr += "<input name = 'name_" + n + "' id = 'name_" + n + "' value = '" + data.Ho_Ten + "' type = 'hidden' /><input  name = 'email_" + n + "'  id = 'email_" + n + "' value = '" + data.Email + "' type = 'hidden' /><input  name = 'title_" + n + "' id = 'title_" + n + "' value = '" + data.title + "' type = 'hidden' />";
                $(tr).appendTo("#addrelist_popup_dm");
            });
        }
    	}
        $("#Dml_Id").val("");
        $("#_Ho_Ten").val("");
    },
    open_popup: function(url){
        popup(url + "modules/cr/popupkhachhang.php?pagetype=popup&mk=1", 800, 500);
        $("#opendmll").attr("disabled", false);
    },
    open_popup_dm: function(url){
        var kha_id = $("#id_kh_dm").val();
        popup(url + 'modules/cr/popup_dmll.php?pagetype=popup&email=1', 800, 500);
    },
    show_popup_import_f_c: function(url, idadd){
    
        var html = "<input onfocus= \"MAIL.getAddress_cr(\'" + url + "\'," + idadd + ");\"  type=\"text\" title=\"KhÃ¡ch hÃ ng\" alt=\"required\" value=\"\" id=\"khachhang\" size=\"30\"  name=\"\" style=\"width: 200px;\"   ><input type=\"text\" value=\"\" id=\"Kha_Id\" name=\"khachhang\" style=\"width: 200px;\">";
        document.getElementById("kh_kh").innerHTML = html;
        document.getElementById("kh_dm").innerHTML = "";
        
        $("#m-p-i-a-c").dialog("open");
        $("#m-p-i-a-c").css("padding", "0px");
        $("#m-p-i-a-c").css("background", "#ffffff");
        document.getElementById("addrelist_popup").innerHTML = "";
        $("#import_startus").text("");
        
        $("#button_2").css("display", "none");
        $("#button_1").css("display", "block");
    },
    show_popup_import_f_dm: function(url, iddadd){
        var html = "<input onfocus = \"MAIL.forcuskhachhang();\"  type=\"text\" title=\"KhÃ¡ch hÃ ng\" alt=\"required\" value=\"\" id=\"khachhang\" size=\"30\"  name=\"\" style=\"width: 200px;\"   ><input type=\"text\" value=\"\" id=\"Kha_Id\" name=\"khachhang\" style=\"width: 200px;\">";
        document.getElementById("kh_dm").innerHTML = html;
        document.getElementById("kh_kh").innerHTML = "";
        $("#m-p-i-a-dm").dialog("open");
        $("#m-p-i-a-dm").css("padding", "0px");
        $("#m-p-i-a-dm").css("background", "#ffffff");
        document.getElementById("addrelist_popup_dm").innerHTML = "";
        $("#import_startus_dm").text("");
        $("#button_4").css("display", "none");
        $("#button_3").css("display", "block");
        
    },
    close_popup_import: function(){
        $('#mail-popup-import-address').dialog('close');
        location.reload(true);
        
    },
    import_email: function(url){
        var urlaction = url + "modules/mail/contact/importaddress";
        
    },
    isEmail: function(s){
        if (s == "") 
            return false;
        if (s.indexOf(" ") > 0) 
            return false;
        if (s.indexOf("@") == -1) 
            return false;
        var i = 1;
        var sLength = s.length;
        if (s.indexOf(".") == -1) 
            return false;
        if (s.indexOf("..") != -1) 
            return false;
        if (s.indexOf("@") != s.lastIndexOf("@")) 
            return false;
        if (s.lastIndexOf(".") == s.length - 1) 
            return false;
		if (s.lastIndexOf(" ") == s.length - 1) 
            return false;
        var str = "abcdefghikjlmnopqrstuvwxyz-@._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        for (var j = 0; j < s.length; j++) 
            if (str.indexOf(s.charAt(j)) == -1) 
                return false;
        return true;
    },
    show_popup_import: function(){
        $("#upload_scn").parent().css("display", "block");
        $("#popup-label-bottun1").css("display", "none");
        $("#popup-label-bottun-import").css("display", "block");
        $("#mail-popup-import-address").dialog("open");
        $("#mail-popup-import-address").css("padding", "0px");
        $("#mail-popup-import-address").css("background", "#ffffff");
        $("#uploadedfile").css("padding-right", "20px");
        $("#table_mail").css("display", "none");
        $("uploadedfile").css("display", "block");
        $("#uploadedfile").text(COREJS._getJsLang('_MESSAGE'));
    },
    delAddressmultil: function(url){
        var n = $("#addrelist input:checked").length;
		var checkright = "";
		var kt = confirm(COREJS._getJsLang("SURE_DEL_EMAIL")+n+COREJS._getJsLang("SURE_DEL_EMAIL_SELECT"));
        var display_to = Number($("#display_to").text()) - n;
        $("#display_to").text(display_to);
		
        var totall = Number($("#totall").text()) - n;
        $("#totall").text(totall);
        if (kt) {
        
            var str = "0";
            $("#addrelist input[type = 'checkbox']").each(function(){
                if (this.checked) {
					 if($(this).next().val()!=1)
					{
						if(checkright!="")
						{
							checkright+=", ";
						}
		
							checkright+=$(this).parent().next().html();
					
					}
					else
					{
					$("#row_" + $(this).val()).remove();
                    str = str + "," + $(this).val();
					}
                    
                }
            });
            var urlaction = url + "/modules/mail/contact/deladressmul?iIdaddress=" + str;
            $.getJSON(urlaction);
			if(checkright!="")
			{
				alert(COREJS._getJsLang("NOT_DEL_ADD"));
				return false;
			}
        }
		$(document).ajaxStop(function(){
			location.reload(true);
		});
    },
    delAddress: function(url, id){
        var kt = confirm(COREJS._getJsLang("SURE_DEL_ADD"));
        if (kt) {
            var display_to = Number($("#display_to").text()) - 1;
            
            $("#display_to").text(display_to);
            var totall = Number($("#totall").text()) - 1
            $("#totall").text(totall);
            var urlaction = url + "/modules/mail/contact/deladdress?iIdaddress=" + id;
            $("#row_" + id).remove();
            $.getJSON(urlaction);
            
                $(document).ajaxStop(function(){
					location.reload(true);
				});
				
        }
        
    },
    sendmailmultiladress: function(url){
        var str = new Array();
		var i = 0;
        $("#addrelist input[type = 'checkbox']").each(function(){
            if (this.checked) {
                str[i]= $(this).val();
				i++;
            }
        });
        window.location = url + "modules/mail/compose&address=" + str;
    },
    save_address_onlistadder: function(url){
    
        var danhxung = $("#danhxung").val();
        var email = $("#email").val();
        var namedisplay = $("#name-display").val();
        var idcontact = $("#id_contact").val();
        var idaddress = $("#id_address").val();
        if (namedisplay == "") {
            alert(COREJS._getJsLang("NAME_NOT_EMPTY"));
            $("#name-display").focus();
            return false;
        }
        if (email==='') {
            alert(COREJS._getJsLang("_EMAIL_EMPTY"));
          $("#email").focus();
          return false;
        }
        if (!this.isEmail(email)) {
              alert(COREJS._getJsLang("EMAIL_FAID"));
            $("#email").focus();
            return false;
        }
        var totall = Number($("#totall").text()) + 1;
        $("#totall").text(totall);
        var totall = Number($("#display_to").text()) + 1;
        $("#display_to").text(totall);
        var optionsource = 1;
        var is_edit = $("#is_edit").val();
        if (is_edit == 1) {
            var urlaction = url + "modules/mail/contact/editaddress?danhxung=" + danhxung + '&email=' + email + '&namedisplay=' + namedisplay + '&idcontact=' + idcontact + '&optionsource=' + optionsource + '&idaddress=' + idaddress;
            $.getJSON(urlaction);
            document.getElementById("td_fisrt_" + idaddress).innerHTML = namedisplay;
            document.getElementById("td-2-" + idaddress).innerHTML = email;
            document.getElementById("title_" + idaddress).innerHTML = danhxung;
            document.getElementById("td-3-" + idaddress).innerHTML = $("#now").val();
            
        }
        else {
            var urlaction = url + "modules/mail/contact/addaddress?danhxung=" + danhxung + '&email=' + email + '&namedisplay=' + namedisplay + '&idcontact=' + idcontact + '&optionsource=' + optionsource;
            $.getJSON(urlaction, null, function(reponse){
                var trinsert = $("#addrelist").find("tr:eq(0)");
                $(reponse).insertBefore(trinsert);
                $("#no_row").remove();
            });
        }
        $("#mail-popup-create-address").dialog("close");
        $("#danhxung").val("");
        $("#email").val("");
        $("#name-display").val("");
        $("#id_contact").val("");
    },
    show_menu_topdown: function(id){
        $("#" + id).toggle(1);
    },
    sorter: function(feild, action){
        $("#field_sort").val(feild);
        if ($("#orderby").val() == 'DESC') {
            $("#orderby").val("ASC");
        }
        else {
            $("#orderby").val("DESC");
        }
        document.forms['frmsorter'].submit();
        
    },
    sentmailmulti: function(url){
        var str = new Array();
		var i= 0;
		var dem = 0;
        $("#contactlist input[type = 'checkbox']").each(function(){
            if (this.checked) {
            	if($(this).attr('class') == 'sudung_1'){
                str[i] =  $(this).val();
				i++;
            	}
            	else
            		{
            		dem++;
            		}
            }
        });
        if(dem!=0)
        	{
        	alert(COREJS._getJsLang('ALERT_KO_SD'));
        	return false;
        	}
        window.location = url + "modules/mail/compose&idcontact=" + str;
    },
    multidelete: function(url){
        var checked = new Array();
        var i = 0;
        var n = 0;
        var kt = 0;
        var urlaction = "";
        var str = new Array();
		var checkright = "";
        var n = $("#contactlist input:checked").length;
        if (n > 0) {
            kt = confirm(COREJS._getJsLang("SURE_DEL_CONTACT")+n+COREJS._getJsLang("SURE_DEL_CONTACT_SELECT"));
        }
		
        if (kt) {
            $("#contactlist input[type = 'checkbox']").each(function(){
                if (this.checked) {
					if ($(this).next().val() == 0) {
					if(checkright!="")
					{
					checkright+=',';
					}
					checkright += " " + $(this).parent().next().html();
					}
					else
					{
					str[i] = $(this).val();
                    $(this).parent().parent().remove();
                    i++;
					}
                    
                }
            });
			var display_to = Number($('#display_to').text());
			display_to = display_to-i;
			$('#footer #display_to').text(display_to);
			$('#footer #totall').text(display_to);
            urlaction = url + "modules/mail/contact/deletecontact?idContact=" + str;
            $.getJSON(urlaction);
			$(document).ajaxStop(function(){
				location.reload(true);
			});
        }
        if (checkright != "") {
		alert(COREJS._getJsLang("NOT_DEL_MB"));
			return false;
		}
    },
    save_address: function(url){
    
        var danhxung = $("#danhxung").val();
        var email = $("#email").val();
        var namedisplay = $("#name-display").val();
        var idcontact = $("#id_contact").val();
        if (namedisplay == "") {
           alert(COREJS._getJsLang("NAME_NOT_EMPTY"));
            $("#name-display").focus();
            return false;
        }
        if (email == "") {
           alert(COREJS._getJsLang("EMAIL_FAID"));
            $("#email").focus();
            return false;
        }
        
        var optionsource = 1;
        var urlaction = url + "modules/mail/contact/addaddress?danhxung=" + danhxung + '&email=' + email + '&namedisplay=' + namedisplay + '&idcontact=' + idcontact + '&optionsource=' + optionsource;
        $.getJSON(urlaction);
        $("#mail-popup-create-address").dialog("close");
        var countaddress = Number(document.getElementById("address_" + idcontact).innerHTML);
        document.getElementById("address_" + idcontact).innerHTML = (countaddress + 1);
        $("#danhxung").val("");
        $("#email").val("");
        $("#name-display").val("");
        $("#id_contact").val("");
    },
    save_contact: function(url){
        var id_contact = $("#option").val();
        var name = $("#contact-name").val();
		if(name=="")
		{
			alert(COREJS._getJsLang('CONTACT_NAME_EMPTY'));
			return false
		}
        var using = $("#using").is(":checked");
        var share = $("#share").is(":checked");
        var option = $("#option").val();
        var totall = Number($("#totall").text()) + 1;
        $("#totall").text(totall);
        var totall = Number($("#display_to").text()) + 1;
        $("#display_to").text(totall);
        if (using) {
            var using = 1;
        }
        else {
            var using = 0;
        }
        if (share) {
            var share = 1;
        }
        else {
            var share = 0;
        }
        if (option != "") {
            var urlAction = url + "modules/mail/contact/update?idContact=" + id_contact + "&name=" + name + "&using=" + using + "&share=" + share;
            $.getJSON(urlAction);
            $("#mail-popup-create-contact").dialog("close");
            var content = document.getElementById("td_fisrt_" + id_contact);
            content.innerHTML = name;
            if (using) {
                var content = document.getElementById("img_1_" + id_contact);
                content.innerHTML = "<img onclick = 'MAIL.change_image_2(\"" + id_contact + "\",\"" + url + "\");' src = '" + url + "/images/check2.png' />";
            }
            else {
                var content = document.getElementById("img_1_" + id_contact);
                content.innerHTML = "<img onclick = 'MAIL.change_image_2(\"" + id_contact + "\",\"" + url + "\");' src = '" + url + "/images/not_check2.png' />";
            }
            
            if (share) {
                var content = document.getElementById("img_2_" + id_contact);
                content.innerHTML = "<img onclick = 'MAIL.change_image_2(\"" + id_contact + "\",\"" + url + "\");' src = '" + url + "/images/check2.png' />";
            }
            else {
                var content = document.getElementById("img_2_" + id_contact);
                content.innerHTML = "<img onclick = 'MAIL.change_image_2(\"" + id_contact + "\",\"" + url + "\");' src = '" + url + "/images/not_check2.png' />";
            }
        }
        else {
            var urlAction = url + "modules/mail/contact/addcontact?name=" + name + "&using=" + using + "&share=" + share;
            $.getJSON(urlAction, null, function(reponse){
                var trinsert = $("#contactlist").find("tr:eq(0)");
               // $(reponse.output).insertBefore(trinsert);
            });
            $("#mail-popup-create-contact").dialog("close");
        }
    },
    delete_contact: function(id, url){
        var kt = confirm(COREJS._getJsLang("_SURE_DEL_MB"));
        if (kt) {
            $("#checkbox_" + id).parent().parent().remove();
            var urlAction = url + "modules/mail/contact/delet?idContact=" + id;
            $.getJSON(urlAction);
            $("#no_row").remove();
        }
		$(document).ajaxStop(function(){
			location.reload(true);
		});
    },
    movedisp: function(id){
        $("#" + id).css("top", "7px");
        $("#" + id).css("left", "-139px");
    },
    menuLayers_show: function(id){
        $("#" + id).css("visibility", "visible");
    },
    menuLayers_hide: function(id){
        $("#" + id).css("visibility", "hidden");
    },
    edit_contact: function(id, content, td, url){
        var con = document.getElementById(td);
        var content = con.innerHTML;
        con.innerHTML = "<input type = 'hidden' value = '" + content + "' id = 'hidden_" + id + "' >" + "<input type = 'text' id = 'input_" + id + "' value = '" + content + "' /> <input type='button' onclick='MAIL.savecontent(" + id + ', " ' + content + ' ", "' + td + '","' + url + '"' + " );' value='LÆ°u' class='teaser-button' style = 'width: 30px;'/> <input type='button' onclick='MAIL.hiden_input(" + id + ',"' + td + '"' + ");' value='há»§y' class='teaser-button' style = 'width: 30px;'> ";
    },
    savecontent: function(id, content, td, url){
    
        var con = document.getElementById(td);
        var input = document.getElementById("input_" + id).value;
        con.innerHTML = input;
        var urlAction = url + "/modules/mail/contact/udateajax?value=" + input + "&field=MB_Contact_name&idContact=" + id;
        $.getJSON(urlAction);
        
    },
    hiden_input: function(id, td){
    
        var con = document.getElementById(td);
        con.innerHTML = document.getElementById("hidden_" + id).value;
    },
    change_image_1: function(id, url,quen){
    	if (quen == 1) {
			var con = document.getElementById(id);
			con.innerHTML = "<img onclick = 'MAIL.change_image_2(\"" + id + "\",\"" + url + "\","+quen+");' src = '" + url + "/images/not_check2.png' />";
			var id = id.substr(6, id.length);
			var urlAction = url + "/modules/mail/contact/udateajax?value=0&field=MB_Using&idContact=" + id;
			
			$.getJSON(urlAction);
			$(document).ajaxStop(function() {
				location.reload(true);
			});
		}
    },
    change_image_2: function(id, url,quen){
		if (quen == 1) {
			var con = document.getElementById(id);
			con.innerHTML = "<img onclick = 'MAIL.change_image_1(\"" + id + "\",\"" + url + "\","+quen+");' src = '" + url + "/images/check2.png' />";
			var id = id.substr(6, id.length);
			var urlAction = url + "/modules/mail/contact/udateajax?value=1&field=MB_Using&idContact=" + id;
			$.getJSON(urlAction);
			$(document).ajaxStop(function() {
				location.reload(true);
			});
		}
    },
    change_image_1_1: function(id, url,quen){
    if (quen == 1) {
		var con = document.getElementById(id);
		con.innerHTML = "<img onclick = 'MAIL.change_image_2_1(\"" + id + "\",\"" + url + "\","+quen+");' src = '" + url + "/images/not_check2.png' />";
		var id = id.substr(6, id.length);
		var urlAction = url + "/modules/mail/contact/udateajax?value=0&field=MB_Share&idContact=" + id;
		$.getJSON(urlAction);
	}
    },
    change_image_2_1: function(id, url,quen){
		if (quen == 1) {
			var con = document.getElementById(id);
			con.innerHTML = "<img onclick = 'MAIL.change_image_1_1(\"" + id + "\",\"" + url + "\","+quen+");' src = '" + url + "/images/check2.png' />";
			var id = id.substr(6, id.length);
			var urlAction = url + "/modules/mail/contact/udateajax?value=1&field=MB_Share&idContact=" + id;
			$.getJSON(urlAction);
		}
    },
    /**
     * select all checkbox contact
     */
    check_all_checkbox: function(id){
    
        var is_check = $("#" + id).is(":checked");
        if (is_check) {
            $("#list-address input[type='checkbox']").attr("checked", true);
        }
        else {
            $("#list-address input[type='checkbox']").attr("checked", false);
        }
        var n = $("table input:checked").length - 1;
        $(".count-check").text("Vá»›i " + n + " Ä‘Ã£ chá»�n");
        if (n > 0) {
            $(".change-header-1").fadeOut("slow");
            $(".change-header-1").hide();
            $(".change-header-2").fadeIn("slow");
            $(".change-header-2").show();
        }
        else {
            $(".change-header-2").fadeOut("slow");
            $(".change-header-2").hide();
            $(".change-header-1").fadeIn("slow");
            $(".change-header-1").show();
        }
    },
    count_check: function(){
        var n = $("table input:checked").length;
        $(".count-check").text("Với " + n + " đã chọn");
        if (n > 0) {
            $(".change-header-1").fadeOut("slow");
            $(".change-header-1").hide();
            $(".change-header-2").fadeIn("slow");
            $(".change-header-2").show();
        }
        else {
            $(".change-header-2").fadeOut("slow");
            $(".change-header-2").hide();
            $(".change-header-1").fadeIn("slow");
            $(".change-header-1").show();
        }
        
    },
    /**
     *  change color picker
     * @author Mrhoang <cao.hoang@gen.vn>
     */
    color_select_picker: function(){
        var texcolor = document.getElementById("text_color_cao").value;
        var gbcolor = document.getElementById("bg_color_cao").value;
        var id_dir = document.getElementById("text_dir").value;
        $("#label-" + id_dir).css("background-color", gbcolor);
        $("#label-" + id_dir).css("color", texcolor);
        $(".dir-" + id_dir).css("background-color", gbcolor);
        $(".dir-" + id_dir).css("color", texcolor);
        gbcolor = gbcolor.substr(1, gbcolor.length);
        texcolor = texcolor.substr(1, texcolor.length);
        url = 'index.php?con=index/udatecolor&textcolor=' + texcolor + "&bgcolor=" + gbcolor + "&directory=" + id_dir;
        $.getJSON(url);
        $("#popup-color-picker").dialog("close");
    },
    show_box_other: function(){
        $('#side-box-other').slideToggle(1);
		return false;
    },
    change_background: function(id_name){
    
        if ($("#" + id_name).is(":checked")) {
            $("#" + id_name).parent().parent().css("background", "#FFFFCC");
        }
        else {
            $("#" + id_name).parent().parent().css("background", "#EFEFEF");
        }
    },
    popup_manage_folder_close: function(){
        $("#popup-foder-manage").dialog("close");
    },
    popup_color_close: function(){
        $("#popup-color-picker").dialog("close");
    },
    show_box_edit_label: function(id){
        $("#" + id).slideToggle(1);
        
    },
    change_color: function(id, Bg_color, text_color){
        var id_dir = id.substr(6, id.length);
        $("#" + id).css("background-color", "#" + Bg_color);
        $(".dir-" + id_dir).css("background-color", "#" + Bg_color);
        url = 'index.php?con=index/udatecolor&textcolor=' + text_color + "&bgcolor=" + Bg_color + "&directory=" + id_dir;
        $.getJSON(url);
    },
    change_star: function(id, url){
        var id_img = id.substr(0, 6);
        var id_msg = id.substr(7, id.length);
        if (id_img == 'star_e') {
            $("#" + id).parent().parent().addClass("mail-star");
            $("#" + id).parent().parent().removeClass("mail-not-star");
            $("#" + id).parent().html("<img id ='star_d_" + id_msg + "' src = '" + url + "/images/icons/star.png'" + 'onclick="MAIL.change_star(\'star_d_' + id_msg + '\',\'' + url + '\');"' + ">");
            url = 'index.php?con=index/changeStar&iMailid=' + id_msg + "&iStarOption=1";
            $.getJSON(url);
        }
        else {
            $("#" + id).parent().parent().addClass("mail-not-star");
            $("#" + id).parent().parent().removeClass("mail-star");
            $("#" + id).parent().html("<img id ='star_e_" + id_msg + "' src = '" + url + "/images/icons/star1.png'" + 'onclick="MAIL.change_star(\'star_e_' + id_msg + '\',\'' + url + '\');"' + ">");
            url = 'index.php?con=index/changeStar&iMailid=' + id_msg + "&iStarOption=0";
            $.getJSON(url);
        }
        
    },
    create_label: function(){
        $("#create-lable").dialog("open");
		 $("#create-lable #label-name").val('');
		  $("#text_color_cao").val('');
       	 $("#bg_color_cao").val('');
       	$("#create-lable").dialog("option", 'title', COREJS._getJsLang('CREAT_NEW_DIR'));
       	$('#label-name').focus();
		 
    },
    showpopup_add_address_add: function(id, id_addre, name, email){
        $("#is_edit").val(1);
        $("#id_contact").val(id);
        $("#id_address").val(id_addre);
        $('.popup-label-header #popup-label-tittle').text(COREJS._getJsLang("SUA_EMAIL"));
        var email = document.getElementById("td-2-" + id_addre).innerHTML;
        $("#email").val(email);
        var title = document.getElementById("title_" + id_addre).innerHTML;
        $("#danhxung").val(title);
        var name = document.getElementById("td_fisrt_" + id_addre).innerHTML;
        $("#name-display").val(name);
        $("#mail-popup-create-address").dialog("open");
        $("#mail-popup-create-address").css("padding", "0px");
        $("#mail-popup-create-address").css("background", "#ffffff");
        $('#option').attr("value", "");
    },
    showpopup_add_address: function(id){
        $("#id_contact").val(id);
        $("#is_edit").val("");
        $("#id_address").val("");
        $("#email").val("");
        $("#danhxung").val("");
        $("#name-display").val("");
        $('.popup-label-header #popup-label-tittle').text(COREJS._getJsLang("CREATE_ADDRESS"));
        $("#mail-popup-create-address").dialog("open");
        $("#mail-popup-create-address").css("padding", "0px");
        $("#mail-popup-create-address").css("background", "#ffffff");
        $('#option').attr("value", "");
		$('#name-display').focus();
    },
    show_popup_create_contact: function(){
        $("#mail-popup-create-contact").dialog("open");
		$("#mail-popup-create-contact #contact-name").val('')
		 $('.popup-label-header #popup-label-tittle').text(COREJS._getJsLang("CREATE_CONTACT"));
        $("#mail-popup-create-contact").css("padding", "0px");
        $("#mail-popup-create-contact").css("background", "#ffffff");
        $('#option').attr("value", "");
		$('#contact-name').focus();
    },
    show_popup_edit_contact: function(id, url){
    
        $("#mail-popup-create-contact").css("padding", "0px");
        $("#mail-popup-create-contact").css("background", "#ffffff");
        $('.popup-label-header #popup-label-tittle').text(COREJS._getJsLang("EDITE_CONTACT"));
        var urlAction = url + "modules/mail/contact/getedit?idContact=" + id;
        $.getJSON(urlAction, null, function(reponse){
            $('#contact-name').val(reponse.MB_Contact_name);
            $('#option').attr("value", reponse.MB_Id_contact_book);
            if (reponse.MB_Using == 1) {
                $("#using").attr("checked", true);
            }
            else {
                $("#using").attr("checked", false);
            }
            if (reponse.MB_Share == 1) {
                $("#share").attr("checked", true);
            }
            else {
                $("#share").attr("checked", false);
            }
        });
        $("#mail-popup-create-contact").dialog("open");
    },
    popup_close: function(){
        $("#create-lable").dialog("close");
    },
    show_popup_color: function(id){
        $("#popup-color-picker").dialog("open");
        $("#popup-color-picker input[type='text'] ").css("display", "none");
        $("#text_dir").val(id);
		
    },
    
    popup_change_name: function(name, id){
        $("#popup_change_name").dialog("open");
		
		
        document.getElementById("popup_mail_box_name").value = name;
        $("#iddir").val(id);
		$("#popup_mail_box_name").focus();
    },
    
    popup_change_name_close: function(){
        $("#popup_change_name").dialog("close");
        
    },
    show_popup_folder_manage: function(){
        $('#popup-foder-manage').dialog("open");
        $('#popup-foder-manage').dialog('option', 'title', COREJS._getJsLang('DIR_MANAGE'));
        $('#create_folder').focus();
    },
    popup_foder_manage_close: function(){
        $("#popup-foder-manage").dialog("close");
    },
    change_dir_name: function(id){
        var text = $("#" + id).text();
        $("#" + id).html("<input type = 'text' name = 'input_" + id + "' id = 'input_" + id + "' value = '" + text + "' >");
    },
    color_label_select: function(color,id){
        $("#label_color").val(color);
		var ischeck = $('#using_color').is(':checked');
		
        $("#text_color_cao").val("");
		$('.label-color-1').css('color','black');
		$('.label-color-1').text('a');
		if (!ischeck) {
			$('#' + id).html('v');
			
			
			$('#' + id).css('color', 'red');
		}
    },
    select_color: function(){
        $("#popup-color-picker").dialog("close");
        var color = $("input[name='icolor']").val();
        $("#label_color").val(color);
        $("#text_color_cao").val("");
    },
    /**
     * chọn các message bằng các link header footer
     * @author Mrhoang <cao.hoang@gen.vn>
     */
    select_message: function(option){
        $('input').attr("checked", false);
        $(".mail-row").css("background", "#EFEFEF");
        $(".readed").css("background", "#ffffff");
        switch (option) {
            case 'ALL':
                $("input[id^= 'Emai_']").attr("checked", true);
                $("input[id^= 'Emai_']").parent().parent().css("background", "#FFFFCC");
                break;
            case 'READED':
                $(".mail-unread input").attr("checked", true);
                $(".mail-unread").css("background", "#FFFFCC");
                break;
            case 'UNREAD':
                $(".readed input").attr("checked", true);
                $(".readed").css("background", "#FFFFCC");
                break;
            case 'STAR':
                $(".mail-star input").attr("checked", true);
                $(".mail-star").css("background", "#FFFFCC");
                break;
            case 'NOSTAR':
                $(".mail-not-star input").attr("checked", true);
                $(".mail-not-star").css("background", "#FFFFCC");
                break;
        };
        
            },
    unselect_message: function(option){
        switch (option) {
            case 'ALL':
                $("input[id^= 'Emai_']").attr("checked", false);
                $("input[id^= 'Emai_']").parent().parent().css("background", "#EFEFEF");
                $(".readed").css("background", "#ffffff");
                break;
            case 'READED':
                break;
        };
   },
   EventKey :function(event){
	   var charCode = (event.which)?event.which:event.keyCode;
	   if(charCode==13){
		   MAIL.search(1);
	   }
   },
   search: function(page){
	   var keyword = document.getElementById("key-find-mail").value;
	   if(keyword!=''){
		   $.ajax({
			   url: COREJS._getJsLang("_GENCRM_URL")+'/modules/mail/search',
			   data: ({
				   keyword: keyword,
				   page: page,
			   }),
			   type: "POST",
			   dataType:"json",
			   beforeSend: function(){
				   COREJS.AlertMsg(COREJS._getJsLang('_LOADING'))
			   },
			   success: function(response){
				   COREJS.CloseMsg();
				   document.getElementById("email-mainpage-wrapper").innerHTML = response.html;
				   document.getElementById("paging_header").innerHTML = response.pagination;
				   document.getElementById("paging_footer").innerHTML = response.pagination;
			   }
		   })
	   }
   },
   Forward : function(id){
	   if($(".tra_loi_lai_thu").hasClass("replyactive")){
		   $(".tra_loi_lai_thu").removeClass("replyactive");
	   }
	   $("#fwd").addClass("replyactive");
	   $.ajax({
		   url: COREJS._getJsLang("_GENCRM_URL")+'/modules/mail/compose/Forward',
		   data: ({
			   ID : id,
		   }),
		   type: "POST",
		   dataType:"json",
		   beforeSend: function(){
			   COREJS.AlertMsg(COREJS._getJsLang('_LOADING'));
		   },
		   success: function(response){
			   COREJS.CloseMsg();
			   document.getElementById("ReplyF").innerHTML = response.html;
			   //a("tinymce");
			   MAILDETAILS.v_fInitEditor();
			   MAIL.callbutton();
			   window.location.href = "#rp";
			   $("#m-cc").click();
		   }
	   })
   },
   
   Reply : function(id)
   {
	   if($(".tra_loi_lai_thu").hasClass("replyactive")){
		   $(".tra_loi_lai_thu").removeClass("replyactive");
	   }
	   $("#rp").addClass("replyactive");
	   $.ajax({
		   url: COREJS._getJsLang("_GENCRM_URL")+'/modules/mail/compose/Reply',
		   data: ({
			   NameFrom : $(".sender").html(),
			   MailFrom : $(".sender-addr").html(),
			   MailTime : document.getElementById("timereply").value,
			   Body : $("#content-pri").html(),
			   Title : $(".tieu_de-email").html(),
			   ID : id,
		   }),
		   type: "POST",
		   dataType:"json",
		   beforeSend: function(){
			   COREJS.AlertMsg(COREJS._getJsLang('_LOADING'));
		   },
		   success: function(response){
			   COREJS.CloseMsg();
			   document.getElementById("ReplyF").innerHTML = response.html;
			   //a("tinymce");
			   MAILDETAILS.v_fInitEditor();
			   MAIL.callbutton();
			   window.location.href = "#rp";
			   $("#m-cc").click();
		   }
	   })
   },
   callbutton: function(){
		$(".bt-g[role='button']").mousedown(function(){
			$(this).css('background','-moz-linear-gradient(center top , #E3E3E3, #F9F9F9)');
			$(this).css('background','-webkit-gradient(linear,0% 40%,0% 70%,from(#E3E3E3),to(#F9F9F9))');
		}).mouseup(function(){
			$(this).css('background','-moz-linear-gradient(center top , #F9F9F9, #E3E3E3)');
			$(this).css('background','-webkit-gradient(linear,0% 40%,0% 70%,from(#F9F9F9),to(#E3E3E3))');
		}).mouseleave(function(){
			$(this).css('background','-moz-linear-gradient(center top , #F9F9F9, #E3E3E3)');
			$(this).css('background','-webkit-gradient(linear,0% 40%,0% 70%,from(#F9F9F9),to(#E3E3E3))');
		})
   },
   searchTrash: function(page){
	   $.ajax({
		   url: COREJS._getJsLang("_GENCRM_URL")+'/modules/mail/search/trash',
		   data: ({
			   keyword: document.getElementById("key-find-mail").value,
			   page: page,
		   }),
		   type: "POST",
		   dataType:"json",
		   beforeSend: function(){
			   COREJS.AlertMsg(COREJS._getJsLang('_LOADING'))
		   },
		   success: function(response){
			   COREJS.CloseMsg();
			   document.getElementById("email-mainpage-wrapper").innerHTML = response.html;
			   document.getElementById("paging_header").innerHTML = response.pagination;
			   document.getElementById("paging_footer").innerHTML = response.pagination;
		   }
	   })
   },
   
   /**
    * Delete one message when view message details
    * 
    * @author	Tran Anh Tuan <tuan.tran@gen.vn>
    * @param	integer the_iMessageId
    * @return	void
    */
   v_fDeleteOneMessage : function(the_iMessageId) {
	   url = COREJS._getJsLang('_GENCRM_URL') + '/modules/mail/details/delete/?mid=' + the_iMessageId;
	   $(window.location).attr('href', url);
   },
   
   /**
    * Show message by directory when in mail details
    * 
    * @author	Tran Anh Tuan <tuan.tran@gen.vn>
    * @param	integer the_DirectoryId
    * @return	void
    */   
   v_fShowByDirectory : function(the_DirectoryId) {
	   if (the_DirectoryId == 0) {
		   url = COREJS._getJsLang('_GENCRM_URL') + '/modules/mail/';
	   }
	   else {
		   url = COREJS._getJsLang('_GENCRM_URL') + '/modules/mail/index/byDirectory/?dir=' + the_DirectoryId;
	   }
	   $(window.location).attr('href', url);
   },
   
   v_fCheckMail : function(the_iCycle){
	   if ('undefined' == the_iCycle || 0 == the_iCycle) {
		   $('#checkmail-accounts-list ul li span.acc-mail-status').each(function(index){
			   $('#acc-cycle_'+index).html('');
		   });
	   }
		url = 'index.php?con=checkmail/index&icycle='+the_iCycle;
	   //url = COREJS._getBaseUrl() + '/modules/mail/checkmail/?icycle=' + the_iCycle;
		$('#acc-cycle_'+the_iCycle).html(COREJS._getJsLang('_MAIL_NEW_MESSAGE_CHECKING')+' <img src="'+COREJS._getJsLang('_GENCRM_URL')+'/images/ajax-loader.gif" align="absmiddle">');
		COREJS.v_fGetJson(url, null,
				function(reponse){
					if(reponse.next > 0) {
						MAIL.v_fCheckMail(reponse.next);
					}
					if (reponse.status != 'ERR') {	
						if (reponse.status > 0) {
							status = '<strong>'+reponse.status+'</strong>';
						}else {
							status = reponse.status;
						}
					}
					else {
						status = COREJS._getJsLang('ERROR');
					}
					
					if (reponse.status != 'ERR') {
						$('#acc-cycle_'+reponse.cid).html(status + ' ' + COREJS._getJsLang('_MAIL_NEW_MESSAGE_NUMBER_ALERT'));
					}
					else {
						$('#acc-cycle_'+reponse.cid).html(status);
					}
			});	   
  },
  
  v_fCheckNewMessage : function(the_iCycle)
  {
		//$("#check_acc").html('');
	  	/*
		$("#info").dialog("open");
		$('#info').dialog({
			height: 500,
			width: 600,
		});
		$('#info .h-d-p').css('width','400px');
		$("#info").css("padding", "0px");
		
		/*
		$.getJSON(url+'modules/mail/index/detectms',null,function(data){
			$("#check_acc").html(data);
		});
		*/
	  COREJS.v_fShowFromPopup('info-checkmail', 'Check mail', 400, 200);
	  MAIL.v_fCheckMail(0);	  
  },
  
  v_finsertDanhXung : function(){
	  html = '{danh_xung}';
	  tinymce.execCommand('mceInsertContent', false, html);
  },
  
  v_finsertHoTen : function(){
	  html = '{ho_ten}';
	  tinymce.execCommand('mceInsertContent', false, html);
  },
  
  v_fdennyReceive : function(){
	  //email = $('#')
	  //html = '<i>Click <b><a href="'+COREJS._getBaseUrl()+'/modules/mail/setting/refused/?email=">' + COREJS._getJsLang('_MAIL_REFUSED_1') + '</a></b> ' + COREJS._getJsLang('_MAIL_REFUSED_2');
	  html = '<i>Click <b><a href="__IGNORE__">' + COREJS._getJsLang('_MAIL_REFUSED_1') + '</a></b> ' + COREJS._getJsLang('_MAIL_REFUSED_2');
	  tinymce.execCommand('mceInsertContent', false, html);
  },
  
  v_fRenameDirectory : function(sz_OldName, i_DirectoryId)
  {
	  COREJS.v_fShowInpagePopup('popup_change_name', COREJS._getJsLang('CHANGE_NAME_DIR'), 200, 150,
			  function(){},
			  function(){
				  url = COREJS._getBaseUrl() + '/modules/mail/directory/rename';
				  sz_Name = $('#sz_DirName').val();
				  data = '{"sz_Name":"'+sz_Name+'","i_DirectoryId":'+i_DirectoryId+'}';
					COREJS.v_fGetJson(url, JSON.parse(data), function(response){
						if (0 == response.e) {
							$('#popup_change_name').dialog('close');
						}
						else {
							COREJS.v_fShowOKDialog(response.e);
						}
					});					  
			  }
	  );
	  $('#sz_DirName').val(sz_OldName).select();
  },
  
  /**
   * Create mail directory
   * @author		Tran Anh Tuan <itanium7000@gmail> or <tuan.tran@gen.vn>
   */
  v_fCreateDirectory : function()
  {
	  COREJS.v_fShowInpagePopup('popup_change_name', COREJS._getJsLang('CHANGE_NAME_DIR'), 200, 150,
			  function(){},
			  function(){
				  // Create
			  }
	  );
  },
  
  /**
   * Show directories management popup
   * 
   * @author		Tran Anh Tuan <itanium7000@gmail.com> or <tuan.tran@gen.vn>
   * @param			none
   * @return		void
   * 		
   */
  v_fDirManagement : function()
  {
	  
  },
  /**
   * Show popup for select contact
   * 
   * @author	Tran Anh Tuan <itanium7000@gmail.com> or <tuan.tran@gen.vn>
   * @param		none
   * @return	void
   */
  v_fShowContactPupup : function()
  {	  
	  COREJS.v_fShowInpagePopup('mail_contact_select', COREJS._getJsLang('SELECT_CONTACT'), 600, 400,
			  function(){},
			  function(){
				// Select mail from single address select  
				if ($('#sl_select_email').is(':checked'))
				{	
					sz_Selected = '';  
				    $(".sl-l-body .sl-l-row div:nth-child(1) span input:checkbox").each(function() {
				        if (this.checked) {
				        	sz_Selected += this.value + ', ';
				        }
				    });				  
				    if ('' == sz_Selected) {
				    	//COREJS.v_fShowOKDialog(COREJS._getJsLang('_MAIL_CTA_SEND_EMPTY'));
				    	$('.sl-l-body').fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200);
				    }
				    else {
					    $('#mail_contact_select').dialog('close');
					    $('#to_addresses').val(sz_Selected);
				    }
				}
				// Select from multiple selectable contact book
				else {
					sz_SelectedBooks = '';
					$("#sl_s_cta_cbx option:selected").each(function() {
						sz_SelectedBooks += $(this).val() + ',';
					});
					if ('' == sz_SelectedBooks) {
						$('#sl_s_cta_cbx').fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200);
					}
					else {
						url = 'loademailsbybooks.php?books=' + sz_SelectedBooks;
						sz_AddressText = '';
						COREJS.v_fGetJson(url, null, function(response){							
							$.each(response, function(i, item) {
								sz_AddressText +=  item.ADD_mail_address + ',';
							});
							$('#mail_contact_select').dialog('close');
							$('#to_addresses').val(sz_AddressText);
						});
					}
				}
			  }
	  );
	  //$(".ui-dialog-titlebar-close").hide();
	  if ($('#sl_select_cta').is(':checked')) {
		  $('#sl_s_cta').show();
		  $('#sl_s_email').hide();
		  if ('0' == $('#sl_cta_loaded').val()) {
			  MAIL.v_fLoadContactBooks();
		  }
		  $('#sl_list_email').hide();
		  $('#sl_s_cta ul li select').focus();
	  }
	  else
	  {
		  $('#sl_s_cta').hide();
		  $('#sl_s_email').show();
		  MAIL.v_fLoadEmail();
		  $('#sl_list_email').show();
		  $('#sl_s_email_keyword').focus();
	  }
	  $('#sl_select_cta').change(function(){
		  $('#sl_list_email').hide();
		  if ($('#sl_select_cta').is(':checked')) {
			  $('#sl_s_cta').show();
			  $('#sl_s_email').hide();
			  if ('0' == $('#sl_cta_loaded').val()) {
				  MAIL.v_fLoadContactBooks();
			  }
		  }
	  });
	  $('#sl_select_email').change(function(){
		  if ($('#sl_select_email').is(':checked')) {
			  $('#sl_s_cta').hide();
			  $('#sl_s_email').show();			  
			  $('#sl_s_cta').hide();
			  MAIL.v_fLoadEmail();
			  if (0 == $('#e_sl_list option').size()) {		
				  MAIL.v_fLoadCoboContactBook();
			  } 		  
			  $('#sl_s_email_keyword').focus();
		  }
		  $('#sl_list_email').show();
	  });	  
	  
	  if ($('#s_in_cta_books').is(':checked')) {
		  if (0 == $('#e_sl_list option').size()) {		
			  MAIL.v_fLoadCoboContactBook();
		  } 
		  $('#c_sl_list').attr('disabled', 'disabled');
	  }
	  else {
		  $('#e_sl_list').attr('disabled', 'disabled');
	  }	  
	  
	  $('#s_in_customer').change(function(){
		  if ($('#s_in_customer').is(':checked')) {
			  $('#c_sl_list').removeAttr('disabled');
			  $('#e_sl_list').attr('disabled', 'disabled');
		  }
	  });
	  $('#s_in_cta_books').change(function(){
		  if ($('#s_in_cta_books').is(':checked')) {
			  $('#e_sl_list').removeAttr('disabled');
			  $('#c_sl_list').attr('disabled', 'disabled'); 			  
		  }
	  });	  
	  // Search button clicked
	  $('#do_search').click(function(){
		  MAIL.v_fDoSearchEmail();
	  });
	  
	  // Check for display button of clear search box
	  $('#sl_s_email_keyword').change(function(){
		  if ($('#sl_s_email_keyword').val().length > 0) {
			  $('#do_search_clr').show();
		  }
		  else {
			  $('#do_search_clr').hide();
		  }
	  });
	  $('#sl_s_email_keyword').keypress(function(){
		  if ($('#sl_s_email_keyword').val().length > 0) {
			  $('#do_search_clr').show();
		  }
		  else {
			  $('#do_search_clr').hide();
		  }
	  });	  
	  // Clear search box
	  $('#do_search_clr').click(function(){
		  $('#sl_s_email_keyword').val('').focus();
		  $('#do_search_clr').hide();
	  });
		$(".sl-l-header div:first span input:checkbox").click(function() {
		    var checkedStatus = this.checked;
		    $(".sl-l-body .sl-l-row div:nth-child(1) span input:checkbox").each(function() {
		        this.checked = checkedStatus;
		    });
		});	  
  },
  
  /**
   * Load contact books list
   * @author	Tran Anh Tuan <itanium7000@gmail.com>
   */
  v_fLoadContactBooks : function()
  {
	  url = COREJS._getBaseUrl()+'/modules/mail/book/loadListBooks';
	  COREJS.v_fGetJson(url, null, function(response){
		  $('#sl_s_cta ul li select').empty();
		  $.each(response, function(i, item) {
			  if (item.n > 0) {
				  $('#sl_s_cta ul li select').append('<option value="'+item.id+'">'+item.name+'</option');
			  }
			  else {
				  $('#sl_s_cta ul li select').append('<option disabled="disabled" value="'+item.id+'">'+item.name+'</option');
			  }
		  });
		  $('#sl_cta_loaded').val('1');
		  //$('#sl_s_cta ul li select option[value=4]').attr('disabled', 'disabled');
	  });	  
  },
  
  /**
   * Load email address from customers or contact books
   * @author	Tran Anh Tuan <itanium7000@gmail.com>
   */
  v_fLoadEmail : function()
  {
	  $('#sl_addr_loaded').val('1');
	  //alert('v_fLoadEmail');
  },
  
  /**
   * Load emails contact book for combobox
   * @author	Tran Anh Tuan <itanium7000@gmail.com>
   */  
  v_fLoadCoboContactBook : function()
  {
	  // Load contact books for combobox
	  url = COREJS._getBaseUrl()+'/modules/mail/book/loadListBooks';
	  COREJS.v_fGetJson(url, null, function(response){
		  $('#e_sl_list').append('<option value="0" style="font-weight:bold;">--- '+COREJS._getJsLang('_MAIL_ON_ALL_BOOLS')+' ---</option');
		  $.each(response, function(i, item) {
			  if (item.n > 0) {
				  $('#e_sl_list').append('<option value="'+item.id+'">'+item.name+'</option');
			  }
			  else {
				  $('#e_sl_list').append('<option disabled="disabled" value="'+item.id+'">'+item.name+'</option');
			  }
		  });
	  });	  
  },
  
  /**
   * Search email address
   * @author	Tran Anh Tuan <itanium7000@gmail.com>
   */
  v_fDoSearchEmail : function()
  {
	  if ($('#s_in_cta_books').is(':checked'))
	  {
		// Search from contact books
		urlSend = "loadEmails.php";
		$.ajax({
			url: urlSend,
			type: "GET",
			data: ({
				iBookId: $('#e_sl_list').val(),
				partName: $('#sl_s_email_keyword').val()
			}),
			
			beforeSend: function(){
			},
			success: function(searchCustomers){
					
		  			
			 			$('#sl_list_email .sl-l-body').html(searchCustomers).show();
		  			
			}
		});
		$('#sl_list_email').show();
	  }
	  else
	  {
		  $i_Option = $('#c_sl_list').val();
		  $i_Option = parseInt($i_Option);
		  
		  // Search from customers
		  var urlSend;
		  switch ($i_Option){
		  	case 0:
		  		urlSend = 'loadEmailOrgCust.php';
		  		break;
		  	case 1:
		  		urlSend = 'loademailsbyInviduals.php';
		  		break;
		  	case 2:
		  		urlSend = 'loademailsbyContactentry.php';
		  		break;
		  }
		  $.ajax({
				url: urlSend,
				type: "GET",
				data: ({
					partName: $('#sl_s_email_keyword').val()
				}),
				
				beforeSend: function(){
				},
				success: function(searchCustomers){
		  			$('#sl_list_email .sl-l-body').html(searchCustomers).show();
				}
		  });
		  $('#sl_list_email').show();
	  }
	  /*
	  COREJS.v_fGetJson(url, null, function(response){
		  $('#sl_list_email .sl-l-body').empty();
		  var icount = 0;
		  $.each(response, function(i, item) {
			  $('#sl_list_email .sl-l-body').append('<div class="sl-l-row"><div><span><input type="checkbox" value="'+item.khachHangInfos.tenKh+' <'+item.khachHangInfos.email+'>" /></span></div><div><span>'+item.khachHangInfos.capNhatCuoi+'</span></div><div><span>'+item.e+'</span></div><div><span>'+item.d+'</span></div></div>');
			  icount++;
		  });
		  $('#ft_total_num').html('<b>'+icount + '</b> ' + COREJS._getJsLang('MAIL_ADD'));
	  });	  
	  $('#sl_list_email').show();
	  */
  }
    
    /*
     * End Mrhoang
     */
};
/*
 * popup create label
 * Mrhoang
 */
$(function(){
	$("#contact").dialog({
        autoOpen: false,
        width: 650,
        modal: true
    });
	$("#popupemailcr").dialog({
        autoOpen: false,
        width: 650,
		height:330,
        modal: true
    });
    $("#mail-popup-create-contact").dialog({
        autoOpen: false,
        height: 160,
        width: 450,
        modal: true,
        open:function(ev,ui){
        	$('#mail-popup-create-contact .popup-label-header').css('width','448px');
        },
        close: function(ev, ui){
        		$(document).ajaxStop(function(){
				location.reload(true);
				});
				}
    });
    $("#mail-popup-create-address").dialog({
        autoOpen: false,
        height: 180,
        width: 450,
        modal: true,
        open:function(ev,ui){
        	$('#mail-popup-create-address .popup-label-header').css('width','448px');
        },
        close: function(ev, ui){
        		$(document).ajaxStop(function(){
				location.reload(true);
				});
				}
    });
    $("#m-p-i-a-c").dialog({
        autoOpen: false,
        height: 230,
        width: 450,
        modal: true,
        open:function(ev,ui){
        	$('#m-p-i-a-c .popup-label-header').css('width','448px');
        	$('#m-p-i-a-c .box-l-n-body').css('width','436px');
        },
    });
    $("#m-p-i-a-dm").dialog({
        autoOpen: false,
        height: 230,
        width: 450,
        modal: true,
        open:function(ev,ui){
        	$('#m-p-i-a-dm .popup-label-header').css('width','448px');
        	$('#m-p-i-a-dm .box-l-n-body').css('width','436px');
        }
    });
    $("#mail-popup-import-address").dialog({
        autoOpen: false,
        height: 200,
        width: 450,
        modal: true,
		closeOnEscape: false,
        close: function(ev, ui){
				location.reload(true);
				}
    });
    $("#create-lable").dialog({
        autoOpen: false,
        height: 200,
        width: 450,
        modal: true,
		close: function(ev, ui){
			$(document).ajaxStop(function(){
				location.reload(true);
			});
				
				}
    });
    $("#popup-color-picker").dialog({
        autoOpen: false,
        //height: 250,
        width: 400,
        modal: true
    });
    $("#popup_change_name").dialog({
        autoOpen: false,
        height: 150,
        width: 450,
        modal: true
    });
    $("#popup-foder-manage").dialog({
        autoOpen: false,
        height: 300,
        width: 450,
        modal: true,
		closeOnEscape: false,
        close: function(ev, ui){
				location.reload(true);
				}
    });
    $("#acc-out-popup").dialog({
        autoOpen: false,
        height: 340,
        width: 450,
        modal: true,
        open: function(ev,ui){
        	$('#acc-out-popup .h-d-p').css('width','448px');
        	
        }
    });
    $("#acc-in-popup").dialog({
        autoOpen: false,
        height: 320,
        width: 450,
        modal: true,
        open: function(ev,ui){
        	$('#acc-in-popup .h-d-p').css('width','448px');
        }
    });
	$("#info").dialog({
        autoOpen: false,
        height: 100,
        width: 400,
        modal: true
    });
});

/*
 * function for sidebal
 * Mrhoang
 */
$('document').ready(function(){
	$('.h-d-p').css('width','100%');
	$('.popup-label-header').css('width','100%');
	$('#popup-label-header').css('width','100%');
	if(Number($('#spam-num').text())!=0)
	{
		
		$('#spam-num').parent().css('font-weight', 'bold');
	}
	$('#menu-1').click(function(){
		$(this).css('display','none');
	});
	
	$('#menu-2').click(function(){
		$(this).css('display','none');
	});
    //------tab-----------
    $(".active-tab").click(function(){
        var this_id = $(this).attr("id");
        $(".active-tab").removeClass("setting-tab-active");
        $("#" + this_id).addClass("setting-tab-active");
        var id_num = this_id.substr(11, this_id.length);
        $(".tab-style").css("display", "none");
        $("#tab-m-" + id_num).css("display", "block");
    });
    //-----end tab------
    
    $("#submit").click(function(){
        $("#acount_nomal").submit();
    });
    $(".f-mn-s").css("cursor", "pointer");
    $("#importxelcon").click(function(){
        $("#table_mail").css("display", "none");
        $("#upload_scn").parent().css("display", "block");
        $("#chi_tiet").css("display", "none");
        $("#mail-popup-import-address").css("height", "200px");
        $("#popup-label-bottun1").css("display", "none");
		$("#download").css("display","block");
        $("#popup-label-bottun-import").css("display", "block");
        $("#uploadedfile").text(COREJS._getJsLang('_MESSAGE'));
    });
    $("#callback").click(function(){
        $('#mail-popup-import-address').dialog('close');
        
        location.reload(true);
    });
    $("#importxel").click(function(){
        $("#popup-label-bottun1").show();
        $("#upload_scn").parent().css("display", "none");
        $(this).parent().hide();
        $("#chitiet").parent().css("display", "block");
        $("#download").css("display","none");
    
    });
    $("#chitiet").click(function(){
        $('#table_mail').css('display', 'block');
        $(this).parent().css("display", "none");
        $("#mail-popup-import-address").css("height", "255px");
        
    });
    $("#list-address input[type = 'checkbox']").attr("checked", false);
    $(".mail-row-mail-box-3").css("padding-left", "3px");
    $(".mail-row-mail-box-3").css("padding-right", "3px");
    $('#email-left-sidebar .item .side-box-body ul li').click(function(){
        $('#email-left-sidebar .item .side-box-body ul li').css("background", "white");
        $('#email-left-sidebar .item .side-box-header p').css("background", "white");
        $(this).css("background", "#BBCCFF");
    });
    $('#email-left-sidebar .item .side-box-header p').click(function(){
        $('#email-left-sidebar .item .side-box-body ul li').css("background", "white");
        $('#email-left-sidebar .item .side-box-header p').css("background", "white");
        $(this).css("background", "#6694E3");
    });
    $("body").click(function(){
        $("div [id^= 'side-bal-box-color-']").hide();
        //var count folder mail
        var count = 3;
        $("#side-box-other").css("display", "none");
        for (i = 1; i <= count; i++) {
            $("#side-bal-box-color-" + i).css("display", "none");
        }
    });
    
    $("#icolor").icolor({
        flat: true,
        onSelect: function(c){
            $("#color-tittle").css("background", c);
            $("#bg_color_cao").val(c);
        },
        showInput: true,
        title: false
    });
    $("#icolor1").icolor({
        flat: true,
        onSelect: function(c){
            $("#color-tittle ul li").css("color", c);
            $("#text_color_cao").val(c);
        },
        showInput: true,
        title: false
    });
    
});
function getFrameByName(name){
    for (var i = 0; i < frames.length; i++) 
        if (frames[i].name == name) 
            return frames[i];
    return null;
}

function uploadDone(name){
    var frame = getFrameByName(name);
    
    if (frame) {
        ret = frame.document.getElementsByTagName("body")[0].innerHTML;
        
        if (ret) {
        
            var json = eval("(" + ret + ")");
            
            
        }
    }
}

/**
 * Automatic get mail from mail server and save into database
 * 
 * @author	Tran Anh Tuan <tuan.tran@gen.vn>
 */
$(document).ready(function () {
	//$.cookie("inbox-msg-num", $('#num_ms').text());
	
	iAutocheck = $('#time_autocheck').val();
	if (iAutocheck > 0)
	{
		setInterval(function () { 
			url = COREJS._getBaseUrl() + '/modules/mail/checkmail/checkmail';
			COREJS.v_fGetJson(url, null,
					function(reponse){
				});		
		}, 30000);	
	}
	
	/*setInterval(function () { 
		url = COREJS._getBaseUrl() + '/modules/mail/checkmail/retrieve';
		COREJS.v_fGetJson(url, null,
				function(reponse){
			});		
	}, 45000);*/
});